//201902104047周润恺
package cn.edu.sdjzu.xg.bysj.service;

import cn.edu.sdjzu.xg.bysj.dao.UserDao;
import cn.edu.sdjzu.xg.bysj.domain.User;
import cn.edu.sdjzu.xg.bysj.domain.authority.Actor;
import lombok.extern.slf4j.Slf4j;
import util.Condition;
import util.JWTHelper;
import util.JdbcHelper;
import util.Pagination;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.Collection;
import java.util.HashMap;
@Slf4j
public final class UserService {
	private UserDao userDao = UserDao.getInstance();
	private static UserService userService = new UserService();
	
	public UserService() {
	}
	
	public static UserService getInstance(){
		return UserService.userService;
	}

	public Collection<User> findAll(Collection<Condition> conditions , Pagination pagination) throws SQLException {
		Connection connection = JdbcHelper.getConn();
		Collection<User> users = userDao.findAll(connection,conditions,pagination);
		JdbcHelper.close(connection);
		return users;
	}
	
	public User getUser(Integer id) throws SQLException {
		Connection connection = JdbcHelper.getConn();
		User user = UserDao.getInstance().find(connection,id);
		JdbcHelper.close(connection);
		return user;
	}
	
	public boolean update(User user) throws SQLException {
		Connection connection = JdbcHelper.getConn();
		boolean updated = userDao.update(connection,user);
		JdbcHelper.close(connection);
		return updated;
	}
	
	public boolean add(User user) throws SQLException {
		Connection connection = JdbcHelper.getConn();
		boolean added = userDao.add(connection,user);
		JdbcHelper.close(connection);
		return added;
	}

	public boolean delete(Integer id) throws SQLException {
		Connection connection = JdbcHelper.getConn();
		boolean deleted = userDao.delete(connection,id);
		JdbcHelper.close(connection);
		return deleted;
	}


	public Actor login(User userToLogin) throws SQLException {
		HashMap<String,String> payload = new HashMap<>();
		payload.put("username",userToLogin.getUsername());
		payload.put("password",userToLogin.getPassword());
		String token = JWTHelper.getToken(payload);
		Connection connection = JdbcHelper.getConn();
		Actor actor = userDao.login(connection, userToLogin);
		JdbcHelper.close(connection);
		actor.setToken(token);
		return actor;
	}
}
